<?php
/**
 *  微信支付回调通知
 *
 * @author 周剑锋 <camfee@yeah.net>
 *
 * Date: 2017/9/1
 * Time: 16:50
 */

define("NO_CHECK", true);
require_once dirname(__DIR__) . '/../../common.inc.php';

use Center\Payment;
use lib\plugins\weixin\Config;
use lib\plugins\weixin\NotifyData;
use Center\CoinLog;

class notice
{
    public function doDefault()
    {
        $xml = file_get_contents("php://input");
        if (empty($xml)) {
            exit(json_encode(["return_code" => 'FAIL', "return_msg" => '没有数据']));
        }

        $notify_data = NotifyData::parseFromXml($xml);
        $weixin_cfg = loadconf('payment/payment')['weixin'];
        $weixin_config = new Config($weixin_cfg);
        if ($notify_data->checkNotifyData($weixin_config->getKey()) === false) {
            echo $notify_data->replayNotify();
            exit;
        }
        $sn = trim($notify_data->getValue('out_trade_no'));
        $payment_info = Payment::getInfoBySN($sn);
        if (empty($payment_info['PaymentId'])) {
            debug_log("weixin notify error, payment not found SN:{$sn}");
            $notify_data->failure('参数错误 out_trade_no');
        }
        $payment_id = $payment_info['PaymentId'];
        $trade_status = $notify_data->getValue('result_code');
        if ($trade_status === 'SUCCESS') {
            if (Payment::isFirstPay($payment_info['UserId'])) {
                CoinLog::addCoinLog($payment_info['UserId'], 2, CoinLog::TYPE_FIRST_PAY);
            }
            $data = [
                'ThirdSN' => $notify_data->getValue('transaction_id'),
                'Content' => $xml,
                'Status' => Payment::STATUS_PAY_SUCCESS,
                'UpdateTime' => date('Y-m-d H:i:s'),
            ];
            if (Payment::paySuccess($sn, $data) !== false) {
                $product_info = \Center\Goods::getInfoByIds($payment_info['ProductId']);
                $user_id = $payment_info['UserId'];
                $coin = (int)$product_info['JCoin'] + (int)$product_info['Donate'];
                pay_succ_log("paySuccess, paymentId:{$payment_id}, userId:{$user_id}");
                if (\Center\User::updateJCoin($user_id, $coin) === false) {
                    pay_fail_log("addCoin failed, paymentId:{$payment_id}, userId:{$user_id}, Coin:{$coin}");
                    Payment::updatePaymentBySN($sn, ['Status' => Payment::STATUS_SEND_GOODS_FAILED]);
                } else {
                    CoinLog::addCoinLog($user_id, $product_info['JCoin'], CoinLog::TYPE_EXCHANGE, false);
                    if (!empty($product_info['Donate'])) {
                        CoinLog::addCoinLog($user_id, $product_info['Donate'], CoinLog::TYPE_PAY_DONATE, false);
                    }
                    pay_succ_log("addCoin, paymentId:{$payment_id}, userId:{$user_id}, Coin:{$coin}");
                }
            } else {
                pay_fail_log("paySuccess failed, paymentId:{$payment_id}, uid:{$payment_info['UserId']}");
            }
        } else {
            debug_log("weixin pay notify failed, SN:{$sn}, status:{$trade_status}", JF_LOG_WARNING);
            Payment::update($payment_id, ['Status' => Payment::STATUS_PAY_FAILURE]);
        }
        echo $notify_data->replayNotify();
        exit;
    }
}

$app->run();